<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <!-- 中心区域 -->
      <a-col :span="24">
        <a-card>
          <div class="mb-20">
            <!-- 查询参数 -->
            <pro-query
              :searchParam="searchParams.params"
              :labelCol="{ span: 10 }"
              :wrapperCol="{ span: 14 }"
              @on-search="search"
              @on-reset="onReset"
            />
          </div>
          <!-- 列表 -->
          <pro-table
            ref="tableRef"
            :fetch="fetch"
            :toolbar="toolbar"
            :columns="columns"
            :operate="operate"
            :param="state.param"
            :pagination="pagination"
            :operationWidth="220"
          />
        </a-card>
      </a-col>
    </a-row>
    <a-modal
      :visible="state.modalVisible"
      v-if="state.modalVisible"
      :title="t('button.generateQrCode')"
      :cancelText="t('button.cancel')"
      :okText="t('button.downloadQrCode')"
      @ok="handleOk"
      @cancel="cancel">
      <div class="qrcode">
        <img :src="state.qrCodeUrl" alt="二维码">
        <!-- <qrcode-vue :value="state.qrCodeUrl" :size="200" level="H" /> -->
      </div>
    </a-modal>
  </page-layout>
</template>
<script>
export default {
  name: "channel-manage"
}
</script>
<script setup>
import { filterEmptyByObject } from "@/tools/common";
import { reactive, onMounted, ref, createVNode, onActivated, nextTick } from "vue";
import { message, modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
import dictEnum from "@/const/dict";
import { downloadIamge } from "@/tools/common";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import { remove, page, mkurl } from "@/api/module/channel-manage";
import moment from "moment";
import QrcodeVue from 'qrcode.vue'
import { useI18n } from "vue-i18n";
import { stat } from "fs";

const removeKey = "remove";
const router = useRouter();
const tableRef = ref();
const { t } = useI18n();

const handleAdd = () => {
  router.push("/market/channel-manage/add");
};
const state = reactive({
  selectedRowKeys: [],
  param: {},
  modalVisible: false,
  qrCodeUrl: 'https://crmh5.lightcourse.com/#/bindasbusiness',
  currentRow: null
});
const toolbar = [
  {
    code: "channel-manage:add",
    label: t("channelManage.label.newChannels"),
    type: "primary",
    event: (selectedRowKeys) => {
      handleAdd();
    },
  },
  {
    code: "",
    label: t("channelManage.label.batchInitiatePayment"),
    type: "primary",
    event: (selectedRowKeys) => {
      handlePay();
    },
  },
  // {
  //   code: "",
  //   label: t("button.batchImport"),
  //   type: "",
  //   event: (selectedRowKeys) => {
  //     handleExport();
  //   },
  // },
];
const pagination = {
  pageNum: 1,
  pageSize: 10,
};
const handleExport = () => {};
const handlePay = () => {};
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys;
};

const fetch = async (param) => {
  const response = await page(param);
  if (response.success) {
    return {
      data: response.data.record,
      total: Number(response.data.total)
    };
  } else {
    return {
      data: [],
    };
  }
};

const columns = [
  { dataIndex: "chnName", key: "chnName", title: t("channelManage.label.channelName"), width: 130, ellipsis: true },
  {
    dataIndex: "chnType",
    key: "chnType",
    title: t("channelManage.label.channelType"),
    width: 130,
    cellRender: (record, data) => {
      const item = dictLists.data[dictEnum.CHANNEL_TYPE]
        ? dictLists.data[dictEnum.CHANNEL_TYPE].find((v) => v.value == data)
        : {};
      return item ? item.label : "";
    },
  },
  {
    dataIndex: "beginTime",
    key: "beginTime",
    width: 160,
    cellRender: (record, data) => {
      const time = data ? moment(data).format("YYYY-MM-DD") : "";
      return time;
    },
    title: t("channelManage.label.cooperationStartTime"),
  },
  {
    dataIndex: "endTime",
    key: "endTime",
    cellRender: (record, data) => {
      const time = data ? moment(data).format("YYYY-MM-DD") : "";
      return time;
    },
    width: 160,
    title: t("channelManage.label.cooperationEndTime"),
  },
  { dataIndex: "num", key: "num", title: t("channelManage.label.numberOfRecommendations|numberOfApplications"), width: 130, },
  {
    dataIndex: "chnTradeStatus",
    key: "chnTradeStatus",
    cellRender: (record, data) => {
      const item = dictLists.data[dictEnum.CHANNEL_STATUS]
        ? dictLists.data[dictEnum.CHANNEL_STATUS].find((v) => v.value == data)
        : {};
      return item ? item.label : "";
    },
    width: 130,
    title: t("channelManage.label.state"),
  },
  { dataIndex: "chnHead", key: "chnHead", title: t("channelManage.label.channelLeader"), width: 150 },
  { dataIndex: "createTime", key: "createTime", title: t("channelManage.label.creationTime"), width: 180 },
];

const operate = [
  {
    label: t("button.detail"),
    width: 200,
    event: (record) => {
      router.push({
        path: "/market/channel-manage/detail",
        query: { id: record.id },
      });
    },
  },
  { code: 'channel-manage:remove', label: t("button.generateQrCode"), event: async(record) => {
      const { data, success } = await mkurl({id: record.id})
      if (success) {
        state.currentRow = record
        state.qrCodeUrl = data;
        state.modalVisible = true
      }
    }, },
  {
    label: t("button.delete"),
    event: function (record) {
      removeMethod(record);
    },
  },
];

const search = (value) => {
  state.param = {
    ...state.param,
    ...filterEmptyByObject(value),
  };
};
const onReset = (value) => {
  state.param = {};
};
const handleOk = () => {
  downloadIamge(state.qrCodeUrl, state.currentRow.chnHead)
}
const cancel = () => {
  state.modalVisible = false
}
/// 删除配置
const removeMethod = (record) => {
  modal.confirm({
    title: "您是否确定要删除此数据?",
    icon: createVNode(ExclamationCircleOutlined),
    okText: "确定",
    cancelText: "取消",
    onOk() {
      remove({ id: record.id }).then((response) => {
        if (response.success) {
          message
            .success({ content: "删除成功", key: removeKey, duration: 1 })
            .then(() => {
              tableRef.value.reload();
            });
        } else {
          message.error({ content: "删除失败", key: removeKey, duration: 1 });
        }
      });
    },
  });
};

let dictLists = reactive({
  data: {},
});
let searchParams = reactive({
  params: [],
});
onActivated(() => {
  tableRef.value.reload();
});
onMounted(async () => {
  dictLists.data = await getDictByCodesReturnObj([
    dictEnum.CHANNEL_TYPE,
    dictEnum.CHANNEL_STATUS,
  ]);
  searchParams.params = [
    {
      key: "chnType",
      type: "select",
      label: t("channelManage.label.channelSource"),
      placeholder: t("placeholder.all"),
      options: dictLists.data[dictEnum.CHANNEL_TYPE],
    },
    { key: "chnName", type: "input", label: t("channelManage.label.channelName"), placeholder: t("placeholder.pleaseEnter") },
    // {
    //   dataIndex: "createTime",
    //   key: "createTime",
    //   keys: ["beginTime", "endTime"],
    //   type: "rangeTime",
    //   label: t("channelManage.label.cooperationTime"),
    //   showTime: { format: "HH:mm:ss" },
    //   format: "YYYY:MM:DD HH:mm:ss",
    //   valueFormat: "YYYY:MM:DD HH:mm:ss",
    //   placeholder: [t("placeholder.startTime"), t("placeholder.endTime")],
    // },
    {
      key: "chnTradeStatus",
      type: "select",
      label: t("channelManage.label.state"),
      placeholder: t("placeholder.all"),
      hidden: true,
      options: dictLists.data[dictEnum.CHANNEL_STATUS],
    },
    {
      key: "chnHead",
      type: "input",
      label: t("channelManage.label.channelLeader"),
      hidden: true,
      placeholder: t("placeholder.pleaseEnter"),
    },
  ];
});
</script>

<style lang="scss" scoped>
.qrcode {
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>
